package com.museum.security;

import cn.hutool.core.util.StrUtil;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTException;
import cn.hutool.jwt.JWTPayload;
import com.museum.utils.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashSet;


/** 自定义一个过滤器用来进行识别jwt
 * @author Akihi
 * @create 2022/11/13
 */
@Slf4j
public class JwtAuthenticationFilter extends BasicAuthenticationFilter {
    private JwtUtil jwtUtil;

    public JwtAuthenticationFilter(AuthenticationManager authenticationManager, JwtUtil jwtUtil) {
        super(authenticationManager);
        this.jwtUtil = jwtUtil;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
                                    FilterChain chain) throws IOException, ServletException {
        /*log.info("jwt 校验 filter");*/
        //获取请求行的相关信息
        /*log.info("getRequestURL  -----> {}", request.getRequestURL());*/
        String jwt = request.getHeader(jwtUtil.getHeader());  //Authorization
        if (StrUtil.isBlankOrUndefined(jwt)) {   //为空或undefined
            chain.doFilter(request, response);
            return;
        }
        //验证token是否正确
        if (!jwtUtil.verifyJwtByToken(jwt)){
            chain.doFilter(request, response);
            return;
        }
        //检查token是否过期
        if (!jwtUtil.isTokenExpired(jwt)){
            chain.doFilter(request, response);
            return;
        }
        /*log.info("jwt 校验成功!");*/
        //解析jwt
        JWT jwtObj = JWT.of(jwt);
        Object username = jwtObj.getPayload(JWTPayload.SUBJECT);
        /*log.info("当前用户-{}", username);*/
        /*获取到用户名之后我们直接把封装成UsernamePasswordAuthenticationToken，
        之后交给SecurityContextHolder参数传递authentication对象，这样后续security就能获取到当前登录的用户信息了，也就完成了用户认证。*/
        UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken
                = new UsernamePasswordAuthenticationToken(username, null, new HashSet<>());
        SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);
        chain.doFilter(request, response);
    }
}
